package com.demo.function.shardingsphere;

import com.alibaba.fastjson.JSON;
import com.demo.function.shardingsphere.annotation.ShardingStrategy;
import com.demo.dao.mapper.UserMapper;
import com.demo.model.entity.db.User;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 强制分片， 通过方法入参指定查询哪个DB
 * @author cyj
 */
@Slf4j
@Service
public class HintStrategyService {

    @Resource
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    @ShardingStrategy(dbIndex = "#dbIndex")
    public void insert(long dbIndex, long userId) {
        User user = new User();
        user.setUserId(userId);
        userMapper.insertSelective(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @ShardingStrategy(dbIndex = "#dbIndex")
    public List<User> queryByUserId(long dbIndex, long userId) {
        return userMapper.queryByUserId(userId);
    }

    /**
     * 通过mybatis Cursor获取大批量数据
     * sharding-jdbc 不支持 jdbc4.1新功能
     * @param dbIndex 指定数据索引
     * @return 用户集合
     * @throws IOException 游标异常信息
     */
    @Transactional(rollbackFor = Exception.class)
    @ShardingStrategy(dbIndex = "#dbIndex")
    public List<User> queryAllByCursor(long dbIndex) throws IOException {
        List<User> list = Lists.newArrayList();
        try(Cursor<User> users = userMapper.queryAll()) {
            users.forEach(user -> list.add(user));
        }
        log.info("游标用户集合：{}", JSON.toJSONString(list));
        return list;
    }
}
